package neusoft.yuejian_11.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import neusoft.yuejian_11.activity.TrainCainiaoActivity;
import neusoft.yuejian_11.activity.TrainGaojiActivity;
import neusoft.yuejian_11.activity.TrainJinjieActivity;
import neusoft.yuejian_11.activity.TrainRumenActivity;
import neusoft.yuejian_11.activity.TrainSearchActivity;
import neusoft.yuejian_11.adapter.TrainListAdapter;
import neusoft.yuejian_11.base.BaseFragment;
import neusoft.yuejian_11.bean.TrainBean;
import neusoft.yuejian_11.listener.RetrofitListener;
import neusoft.yuejian_11.model.TrainModel;
import neusoft.yuejian_11.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class TrainListFragment extends BaseFragment implements RetrofitListener{
    private RecyclerView recyclerView;
    private TrainListAdapter trainListAdapter;
    private ImageButton imageButtonSearch;
    private Button jinjieButton;
    private Button cainiaoButton;
    private  Button rumenButton;
    private  Button gaojiButton;

    private View rView;
    private ViewPager viewPager;
    private List<ImageView> imageViews;
    private List<View> views;
    private int currentItem;
    private int oldPosition = 0;//记录上一次点的位置
    private int[] imageIds = new int[]{
            R.drawable.train1,
            R.drawable.train2,
            R.drawable.train3
    };//存放图片的id
    private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;


    public TrainListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        imageButtonSearch = (ImageButton) view.findViewById(R.id.imageButtom_search);
        recyclerView = view.findViewById(R.id.recyclerView);
        cainiaoButton= (Button) view.findViewById(R.id.button_c);
        rumenButton= (Button) view.findViewById(R.id.button_r);
        gaojiButton= (Button) view.findViewById(R.id.button_g);
        jinjieButton= (Button) view.findViewById(R.id.button_j);

        initEvents();//点击事件处理
        initData();//网络获取
    }

    private void initEvents() {
        imageButtonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity().getApplicationContext(), TrainSearchActivity.class);
                getActivity().startActivity(intent);
            }
        });

        cainiaoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(getActivity(),TrainCainiaoActivity.class);
                startActivityForResult(intent,1 );//requestCode
            }
        });
        jinjieButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(getActivity(),TrainJinjieActivity.class);
                startActivityForResult(intent,1 );//requestCode
            }
        });
        gaojiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(getActivity(),TrainGaojiActivity.class);
                startActivityForResult(intent,1 );//requestCode
            }
        });
        rumenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(getActivity(),TrainRumenActivity.class);
                startActivityForResult(intent,1 );//requestCode
            }
        });
    }

    private void initData() {
        TrainModel trainModel = new TrainModel();
        trainModel.trainList(this);
    }

    @Override
    public void onSuccess(Object o, int flag) {
        if (getActivity() != null){
            List<TrainBean> trainBeanList = (List<TrainBean>) o;
            trainListAdapter = new TrainListAdapter(getActivity(),trainBeanList);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(trainListAdapter);
            recyclerView.setItemAnimator(new DefaultItemAnimator());
        }
    }

    @Override
    public void onFail() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rView=inflater.inflate(R.layout.fragment_train_list, null);
        setView();
        return rView;
    }


    private void setView() {
        viewPager = (ViewPager) rView.findViewById(R.id.viewPager);

        //显示的图片
        imageViews = new ArrayList<ImageView>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            imageViews.add(imageView);
        }
        //显示的小点
        views = new ArrayList<View>();
        views.add(rView.findViewById(R.id.rr1));
        views.add(rView.findViewById(R.id.rr2));
        views.add(rView.findViewById(R.id.rr3));

        adapter = new ViewPagerAdapter();
        viewPager.setAdapter(adapter);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                views.get(position).setBackgroundResource(R.drawable.ic_rr);
                views.get(oldPosition).setBackgroundResource(R.drawable.ic_rr);

                oldPosition = position;
                currentItem = position;

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /*定义的适配器*/

    public class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return imageViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub
//          super.destroyItem(container, position, object);
//          view.removeView(view.getChildAt(position));
//          view.removeViewAt(position);
            view.removeView(imageViews.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(imageViews.get(position));
            return imageViews.get(position);
        }

    }

    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }


    /**
     * 图片轮播任务
     * @author liuyazhuang
     *
     */
    private class ViewPageTask implements Runnable{

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            viewPager.setCurrentItem(currentItem);
        };
    };
    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if(scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }

}
